package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.Db;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.SetmealVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {


    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public void saveWithDishs(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        this.save(setmeal);
        Long id = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        setmealDishes.forEach(s -> s.setSetmealId(id));
        Db.saveBatch(setmealDishes);
    }

    @Override
    public PageResult getSetmealsByPage(SetmealPageQueryDTO setmealPageQueryDTO) {

        Setmeal setmeal = new Setmeal();

        int page = setmealPageQueryDTO.getPage();
        int pageSize = setmealPageQueryDTO.getPageSize();
        String name = setmealPageQueryDTO.getName();
        Integer categoryId = setmealPageQueryDTO.getCategoryId();
        Integer status = setmealPageQueryDTO.getStatus();

        BeanUtils.copyProperties(setmealPageQueryDTO, setmeal);
        log.info(setmeal.toString());
        Page<Setmeal> pageInfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotBlank(name), Setmeal::getName, name)
                .eq(categoryId != null, Setmeal::getCategoryId, categoryId)
                .eq(status != null, Setmeal::getStatus, status)
                .orderByDesc(Setmeal::getUpdateTime);
        setmealMapper.selectPage(pageInfo, qw);


        Page<SetmealVO> setmealVOPage = new Page<>();
        BeanUtils.copyProperties(pageInfo, setmealVOPage, "records");

        List<Setmeal> records = pageInfo.getRecords();
        List<SetmealVO> setmealVOS = records.stream()
                .map(item -> {
                    SetmealVO setmealVO = new SetmealVO();
                    //将Setmeal对象拷贝给SetmealVO对象
                    BeanUtils.copyProperties(item, setmealVO);
                    //获取categoryId对应的categoryName
                    Long categoryId1 = item.getCategoryId();
                    Category category = Db.getById(categoryId1, Category.class);
                    setmealVO.setCategoryName(category.getName());
                    return setmealVO;
                }).collect(Collectors.toList());
        setmealVOPage.setRecords(setmealVOS);
        return new PageResult(setmealVOPage.getTotal(), setmealVOPage.getRecords());
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> qw = new LambdaQueryWrapper<>();
        qw.in(Setmeal::getId, ids)
                .eq(Setmeal::getStatus, StatusConstant.ENABLE);
        boolean exists = setmealMapper.exists(qw);

        if (exists) {
            throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
        }
        this.removeBatchByIds(ids);
    }

    @Override
    public SetmealVO getByIdWithDishs(Long id) {
        Setmeal setmeal = this.getById(id);
        SetmealVO setmealVO = new SetmealVO();
        BeanUtils.copyProperties(setmeal, setmealVO);

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper);
        setmealVO.setSetmealDishes(setmealDishes);
        return setmealVO;
    }

    @Override
    public void updateWithDishs(SetmealDTO setmealDTO) {
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(setmealDTO, setmeal);

        this.updateById(setmeal);

        Long id = setmeal.getId();
        List<SetmealDish> setmealDishes = setmealDTO.getSetmealDishes();

        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        setmealDishMapper.delete(queryWrapper);

//        this.updateById(setmeal);


        if (CollectionUtils.isNotEmpty(setmealDishes)) {
            //缺少套餐id，需要设置套餐id ----------
            //1. 采用Lambda表达式进行套餐id设置
            setmealDishes.forEach(s -> s.setSetmealId(id));

//            //2. 使用Stream流
//            setmealDishes = setmealDishes.stream().map(s -> {
//                s.setSetmealId(id);
//                return s;
//            }).collect(Collectors.toList());

            Db.saveBatch(setmealDishes);
        }
    }

    /**
     * 启用禁用套餐
     *
     * @param status 页面传来的参数，点击禁用--status=0     点击启用--status=1
     * @param id
     */
    @Override
    public void updateStatus(Integer status, long id) {


//        Setmeal setmeal = this.getById(id);

        //根据套餐id在SetmealDish表查询到对应的数据
        LambdaQueryWrapper<SetmealDish> qw = new LambdaQueryWrapper<>();
        qw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(qw);

        if (CollectionUtils.isNotEmpty(setmealDishes)) {
            for (SetmealDish s : setmealDishes) {
                Long dishId = s.getDishId();
                Dish dish = Db.getById(dishId, Dish.class);
                if (dish.getStatus() == StatusConstant.DISABLE) {
                    throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            }
            Setmeal temp = Setmeal.builder()
                    .id(id)
                    .status(status)
                    .build();
            setmealMapper.updateById(temp);
            return;
        }
        throw new DeletionNotAllowedException(MessageConstant.UNKNOWN_ERROR);

    }

    /**
     * 条件查询
     *
     * @param setmeal
     * @return
     */
    public List<Setmeal> list(Setmeal setmeal) {

        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(setmeal.getName() != null, Setmeal::getName, setmeal.getName())
                .eq(setmeal.getCategoryId() != null, Setmeal::getCategoryId, setmeal.getCategoryId())
                .eq(setmeal.getStatus() != null, Setmeal::getStatus, setmeal.getStatus());

        return setmealMapper.selectList(queryWrapper);

    }

    /**
     * 根据套餐id查询菜品选项
     *
     * @param id
     * @return
     */

    public List<DishItemVO> getDishItemById(Long id) {
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, id);

        return setmealDishMapper.selectList(queryWrapper)
                .stream()
                .map(s -> {
                    DishItemVO itemVO = new DishItemVO();
                    BeanUtils.copyProperties(Db.getById(s.getDishId(), Dish.class),itemVO);
                    itemVO.setCopies(s.getCopies());
                    return itemVO;
                })
                .collect(Collectors.toList());
    }
//    public List<DishItemVO> getDishItemById(Long id) {
//        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(SetmealDish::getSetmealId, id);
//        List<SetmealDish> setmealDishes = setmealDishMapper.selectList(queryWrapper);
//
//        //根据套餐id在SetmealDish表查询到对应的数据
//        List<DishItemVO> dishItemVOS = new ArrayList<>();
//
//        dishItemVOS = setmealDishes.stream().map(s -> {
//            Long dishId = s.getDishId();
//            Dish dish = Db.getById(dishId, Dish.class);
//            DishItemVO itemVO = new DishItemVO();
//            BeanUtils.copyProperties(dish, itemVO);
//            itemVO.setCopies(s.getCopies());
//            return itemVO;
//        }).collect(Collectors.toList());
//
//        return dishItemVOS;
//    }
}